const schema = require("../dao/chatSchema"),
    roomSchema = require("../dao/roomSchema"),
    userSchema = require("../dao/userSchema");

function addChat(inner, isImg, isVoice, userId, roomId, cb) {
    let chat = new schema({
        inner: inner,
        isImg: isImg,
        isVoice: isVoice,
        from: userId,
        time: new Date()
    });
    let saveChat = chat.save();
    let findRoom = roomSchema.findById(roomId);
    Promise.all([saveChat, findRoom]).then(([chatRes, roomRes]) => {
        roomRes.chats.push(chatRes);
        roomRes.save().then(res => {
            schema
                .findById(chatRes._id)
                .populate("from")
                .exec()
                .then(val => {
                    cb({ message: "消息发送成功", ok: true, data: val });
                });
        });
    });
}

module.exports = {
    add: addChat
};
